<?php
session_start();

// 检查用户是否已登录
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

// 用户存在性校验
$users_file = 'users.json';
if (file_exists($users_file)) {
    $users = json_decode(file_get_contents($users_file), true);
    $found = false;
    if (is_array($users)) {
        foreach ($users as $user) {
            if ($user['username'] === $_SESSION['username']) {
                $found = true;
                break;
            }
        }
    }
    if (!$found) {
        session_destroy();
        header("Location: login.php");
        exit();
    }
}

require_once 'crypto.php';

// 处理添加、编辑、删除操作
$data_file = 'db.json';
$items = [];

if (file_exists($data_file)) {
    $encrypted_data = file_get_contents($data_file);
    $items = Crypto::decrypt($encrypted_data) ?? [];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add':
                $new_item = [
                    'id' => time(),
                    'name' => $_POST['name'],
                    'db_name' => $_POST['db_name'],
                    'address' => $_POST['address'],
                    'username' => $_POST['username'],
                    'password' => $_POST['password']
                ];
                $items[] = $new_item;
                break;
            
            case 'edit':
                foreach ($items as &$item) {
                    if ($item['id'] == $_POST['id']) {
                        $item['name'] = $_POST['name'];
                        $item['db_name'] = $_POST['db_name'];
                        $item['address'] = $_POST['address'];
                        $item['username'] = $_POST['username'];
                        $item['password'] = $_POST['password'];
                        break;
                    }
                }
                break;
            
            case 'delete':
                foreach ($items as $key => $item) {
                    if ($item['id'] == $_POST['id']) {
                        unset($items[$key]);
                        break;
                    }
                }
                $items = array_values($items); // 重新索引数组
                break;
        }
        // 加密数据并保存
        $encrypted_data = Crypto::encrypt($items);
        file_put_contents($data_file, $encrypted_data);
        header('Location: index.php');
        exit();
    }
}

function mask_middle($str) {
    $len = mb_strlen($str);
    if ($len <= 4) return str_repeat('*', $len);
    $start = mb_substr($str, 0, 2);
    $end = mb_substr($str, -2);
    return $start . str_repeat('*', $len - 4) . $end;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>数据库连接管理</title>
    <meta charset="UTF-8">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f0f2f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .welcome {
            margin: 0;
        }
        .header-links {
            display: flex;
            gap: 20px;
            align-items: center;
        }
        .header-link {
            color: #1677ff;
            text-decoration: none;
        }
        .header-link:hover {
            text-decoration: underline;
        }
        .logout {
            color: #1677ff;
            text-decoration: none;
        }
        .logout:hover {
            text-decoration: underline;
        }
        .add-btn {
            background-color: #1677ff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin-bottom: 20px;
        }
        .add-btn:hover {
            background-color: #4096ff;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #fafafa;
            white-space: nowrap;
        }
        td {
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .action-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 5px;
            white-space: nowrap;
        }
        .edit-btn {
            background-color: #52c41a;
            color: white;
        }
        .delete-btn {
            background-color: #ff4d4f;
            color: white;
        }
        .access-btn {
            background-color: #1677ff;
            color: white;
        }
        .test-btn {
            background-color: #722ed1;
            color: white;
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 20px;
            border-radius: 8px;
            width: 80%;
            max-width: 600px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .modal-buttons {
            text-align: right;
            margin-top: 20px;
        }
        .modal-buttons button {
            padding: 8px 16px;
            margin-left: 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .save-btn {
            background-color: #1677ff;
            color: white;
        }
        .cancel-btn {
            background-color: #f5f5f5;
            color: #333;
        }
        .password-field {
            position: relative;
        }
        .toggle-password {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            cursor: pointer;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2 class="welcome">欢迎，<?php echo htmlspecialchars($_SESSION['username']); ?></h2>
            <div class="header-links">
                <?php if (isset($_SESSION['role']) && in_array($_SESSION['role'], ['admin', 'manager'])): ?>
                <a href="dictionary_manage.php" class="header-link">字典维护</a>
                <a href="user_manage.php" class="header-link">用户管理</a>
                <?php endif; ?>
                <a href="#" class="header-link" onclick="showChangePasswordModal(); return false;">修改密码</a>
                <a href="logout.php" class="logout">退出登录</a>
            </div>
        </div>
        
        <?php if (isset($_SESSION['role']) && in_array($_SESSION['role'], ['admin', 'manager'])): ?>
        <button class="add-btn" onclick="showModal('add')">添加新连接</button>
        <?php endif; ?>
        
        <table>
            <thead>
                <tr>
                    <th>名称</th>
                    <th>库名</th>
                    <th>地址</th>
                    <th>帐号</th>
                    <th>密码</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $item): ?>
                <tr>
                    <td><?php echo htmlspecialchars($item['name']); ?></td>
                    <td><?php echo htmlspecialchars($item['db_name']); ?></td>
                    <td><?php echo htmlspecialchars(mask_middle($item['address'])); ?></td>
                    <td><?php echo htmlspecialchars(mask_middle($item['username'])); ?></td>
                    <td>********</td>
                    <td>
                        <button class="action-btn access-btn" onclick="accessItem(<?php echo htmlspecialchars(json_encode($item)); ?>)">访问</button>
                        <?php if (isset($_SESSION['role']) && in_array($_SESSION['role'], ['admin', 'manager'])): ?>
                        <button class="action-btn edit-btn" onclick="showModal('edit', <?php echo htmlspecialchars(json_encode($item)); ?>)">编辑</button>
                        <button class="action-btn delete-btn" onclick="deleteItem(<?php echo $item['id']; ?>)">删除</button>
                        <?php endif; ?>
                        <button class="action-btn test-btn" onclick="testConnection(<?php echo htmlspecialchars(json_encode($item)); ?>)">测试</button>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- 添加/编辑模态框 -->
    <div id="modal" class="modal">
        <div class="modal-content">
            <h3 id="modalTitle">添加新连接</h3>
            <form id="itemForm" method="POST">
                <input type="hidden" name="action" id="formAction" value="add">
                <input type="hidden" name="id" id="formId">
                <div class="form-group">
                    <label for="name">名称：</label>
                    <input type="text" id="name" name="name" required>
                </div>
                <div class="form-group">
                    <label for="db_name">库名：</label>
                    <input type="text" id="db_name" name="db_name" required>
                </div>
                <div class="form-group">
                    <label for="address">地址：</label>
                    <input type="text" id="address" name="address" required>
                </div>
                <div class="form-group">
                    <label for="username">帐号：</label>
                    <input type="text" id="username" name="username" required>
                </div>
                <div class="form-group">
                    <label for="password">密码：</label>
                    <div class="password-field">
                        <input type="password" id="password" name="password" required>
                        <button type="button" class="toggle-password" onclick="togglePassword()">显示</button>
                    </div>
                </div>
                <div class="modal-buttons">
                    <button type="button" class="cancel-btn" onclick="hideModal()">取消</button>
                    <button type="submit" class="save-btn">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 修改密码模态框 -->
    <div id="changePasswordModal" class="modal">
        <div class="modal-content">
            <h3>修改密码</h3>
            <form id="changePasswordForm">
                <div class="form-group">
                    <label for="old_password">原密码：</label>
                    <div class="password-field">
                        <input type="password" id="old_password" name="old_password" required>
                        <button type="button" class="toggle-password" onclick="togglePassword('old_password')">显示</button>
                    </div>
                </div>
                <div class="form-group">
                    <label for="new_password">新密码：</label>
                    <div class="password-field">
                        <input type="password" id="new_password" name="new_password" required>
                        <button type="button" class="toggle-password" onclick="togglePassword('new_password')">显示</button>
                    </div>
                </div>
                <div class="form-group">
                    <label for="confirm_password">确认新密码：</label>
                    <div class="password-field">
                        <input type="password" id="confirm_password" name="confirm_password" required>
                        <button type="button" class="toggle-password" onclick="togglePassword('confirm_password')">显示</button>
                    </div>
                </div>
                <div class="modal-buttons">
                    <button type="button" class="cancel-btn" onclick="hideChangePasswordModal()">取消</button>
                    <button type="submit" class="save-btn">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Toast提示框 -->
    <div id="toast" style="display:none;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:9999;min-width:180px;padding:18px 32px;background:rgba(0,0,0,0.85);color:#fff;border-radius:8px;font-size:18px;box-shadow:0 2px 12px rgba(0,0,0,0.18);text-align:center;pointer-events:none;transition:all 0.3s;"></div>

    <script>
        function showModal(action, item = null) {
            const modal = document.getElementById('modal');
            const form = document.getElementById('itemForm');
            const title = document.getElementById('modalTitle');
            
            if (action === 'add') {
                title.textContent = '添加新连接';
                form.reset();
                document.getElementById('formAction').value = 'add';
            } else if (action === 'edit' && item) {
                title.textContent = '编辑连接';
                document.getElementById('formAction').value = 'edit';
                document.getElementById('formId').value = item.id;
                document.getElementById('name').value = item.name;
                document.getElementById('db_name').value = item.db_name;
                document.getElementById('address').value = item.address;
                document.getElementById('username').value = item.username;
                document.getElementById('password').value = item.password;
            }
            
            modal.style.display = 'block';
        }

        function hideModal() {
            document.getElementById('modal').style.display = 'none';
        }

        function deleteItem(id) {
            if (confirm('确定要删除这个连接吗？')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="${id}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }

        function togglePassword(fieldId) {
            const passwordInput = document.getElementById(fieldId);
            const toggleButton = passwordInput.nextElementSibling;
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                toggleButton.textContent = '隐藏';
            } else {
                passwordInput.type = 'password';
                toggleButton.textContent = '显示';
            }
        }

        function accessItem(item) {
            window.location.href = 'db_manage.php?id=' + item.id;
        }

        function testConnection(item) {
            // 创建测试连接的请求
            fetch('test_connection.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(item)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('连接成功！','success');
                } else {
                    showToast('连接失败：' + data.message,'error');
                }
            })
            .catch(error => {
                showToast('测试连接时发生错误：' + error.message,'error');
            });
        }

        function showChangePasswordModal() {
            document.getElementById('changePasswordModal').style.display = 'block';
        }

        function hideChangePasswordModal() {
            document.getElementById('changePasswordModal').style.display = 'none';
            document.getElementById('changePasswordForm').reset();
        }

        document.getElementById('changePasswordForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            
            fetch('change_password.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                showToast(data.message);
                if (data.success) {
                    hideChangePasswordModal();
                }
            })
            .catch(error => {
                showToast('发生错误，请稍后重试');
            });
        });

        function showToast(message) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.style.display = 'block';
            setTimeout(() => {
                toast.style.display = 'none';
            }, 3000);
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('modal');
            if (event.target == modal) {
                hideModal();
            }
        }
    </script>
</body>
</html> 